<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{

    /**
     * 登录界面
     */
    public function login()
    {
        return view('auth.login');
    }


    /**
     * 登录
     * @param Request $request
     * @return void
     */
    public function loginLogic(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'password' => 'required'
        ], [
            'name.required' => '用户名不能为空',
            'password.required' => '密码不能为空'
        ]);

        if (auth()->attempt(['name' => $request->name, 'password' => $request->password])) {
            return redirect('/');
        } else {
            return back()->withErrors(['name' => '用户名或密码错误']);
        }

    }


    /**
     * 注册界面
     */
    public function register()
    {
        return view('auth.register');
    }


    /**
     * 注册界面
     */
    public function registerLogic(Request $request)
    {
        // 验证
        $this->validate($request, [
            'name' => 'required|unique:users',
            'nickname' => 'required',
            'password' => 'required|confirmed',
            'is_manage' => 'required'
        ], [
            'name.unique' => '用户名已存在',
            'name.required' => '用户名不能为空',
            'nickname.required' => '昵称不能为空',
            'password.required' => '密码不能为空',
            'password.confirmed' => '两次密码不一致',
            'is_manage.required' => '请选择用户身份'
        ]);
        $data = $request->all();
        $data['password'] = bcrypt($data['password']);
        $data['level_id'] = 1;
        if ($data['is_manage'] == 2) {
            // 0 待审核
            $data['status'] = 0;
        } else {
            $data['status'] = 1;
        }

        $user = User::create($data);
        // 登录
        auth()->login($user);
        return redirect('/')->with('success', '注册成功');
    }


    public function logout(Request $request)
    {
        auth()->logout();
        return redirect('/');
    }

}
